#! /bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# Check if user is root
if [ $(id -u) != "0" ]; then
echo "Error: You must be root to run this script!"
exit 1
fi

echo "+-------------------------------------------+"
echo "|             Manager for WebApp            |"
echo "+-------------------------------------------+"

arg1=$1
arg2=$2

echo $arg1;
echo $arg2;

APP_DIR=/www/python/host/

uwsgi_start() {
	echo "Starting uWSGI..."
	if [ -f "/tmp/uwsgi.pid" ]; then
		uwsgi --stop /tmp/uwsgi.pid >/dev/null 2>&1
		rm -f /tmp/uwsgi.pid
	fi
	nohup uwsgi --ini ${APP_DIR}config.ini --pidfile /tmp/uwsgi.pid >/dev/null 2>&1 &
}

uwsgi_stop() {
	echo "Stoping UWSGI..."
	uwsgi --stop /tmp/uwsgi.pid
	rm -f /tmp/uwsgi.pid
}

uwsgi_reload() {
	echo "Reload UWSGI..."
	uwsgi --reload /tmp/uwsgi.pid
}

webapp_start()
{
    echo "Starting webapp..."
    /etc/init.d/nginx start
    uwsgi_start
}

webapp_stop()
{
    echo "Stoping webapp..."
    /etc/init.d/nginx stop
    uwsgi_stop
}

webapp_reload()
{
    echo "Reload webapp..."
    /etc/init.d/nginx reload
    uwsgi_reload
}

webapp_kill()
{
    echo "Kill nginx,uWSGI process..."
    killall nginx
    killall uwsgi
    echo "done."
}

webapp_status()
{
    /etc/init.d/nginx status
    if [ -f "/tmp/uwsgi.pid" ]; then
        echo "uwsgi is runing!"
    else
        echo "uwsgi is stop!"
    fi
}


case "${arg1}" in
    start)
        webapp_start
        ;;
    stop)
        webapp_stop
        ;;
    restart)
        webapp_stop
        sleep 1s
        webapp_start
        ;;
    reload)
        webapp_reload
        ;;
    kill)
        webapp_kill
        ;;
    status)
        webapp_status
        ;;
    nginx)
        /etc/init.d/nginx ${arg2}
        ;;
    *)
        echo "Usage: webapp {start|stop|reload|restart|kill|status}"
        echo "Usage: webapp nginx {start|stop|reload|restart|kill|status}"
esac
exit
